﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms.DataVisualization.Charting;
using System.Timers;
using System.IO;
using Microsoft.Win32;

namespace BDSim
{
    /// <summary>
    /// UserMonitorView.xaml 的交互逻辑
    /// </summary>
    public partial class DopEvaluationView : UserControl, ILayoutContent
    {
        #region//构造函数
        public DopEvaluationView()
        {
            InitializeComponent();
        }
        #endregion

        #region//成员

        string chk_imagePath = string.Format("{0}\\Resources\\Images\\chk_checked.png", Directory.GetCurrentDirectory());//取得选择图片的绝对路径

        string unchk_imagePath = string.Format("{0}\\Resources\\Images\\chk_unchecked.png", Directory.GetCurrentDirectory());//取得未选择图片的绝对路径

        public DopEnum EvaluationType;

        DopAnalysisResult dopValue;
        #endregion

        #region //初始化表格及表格内的曲线参数

        /// <summary>
        /// 初始化表格及表格内的曲线参数
        /// </summary>
        /// <param name="chartType"></param>
        /// <param name="userFlag"></param>
        public void InitCharts()
        {
            Series SatPosX = new Series("最大值") { ChartType = SeriesChartType.FastLine ,Color = System.Drawing.Color.Red};
            Series SatPosY = new Series("最小值") { ChartType = SeriesChartType.FastLine, Color = System.Drawing.Color.Green };
            Series SatPosZ = new Series("平均值") { ChartType = SeriesChartType.FastLine, Color = System.Drawing.Color.Blue };
            Series SatPosVx = new Series("方差") { ChartType = SeriesChartType.FastLine, Color = System.Drawing.Color.PaleVioletRed};
            chart2.Series.Add(SatPosX);
            chart2.Series.Add(SatPosY);
            chart2.Series.Add(SatPosZ);
            chart2.Series.Add(SatPosVx);
            SetLegend(chart2);
            chart2.ChartAreas[0].AxisX.Title = "仿真步数";
            //当表格类型应用为实时监控时，初始化定时器,
        }
        #endregion

        #region//显示DOP评估值走势
        /// <summary>
        /// 显示DOP评估值走势
        /// </summary>
        /// <param name="dopValue"></param>
        public void DisplayDopEvaluation(DopAnalysisResult dopValue)
        {
            this.dopValue = dopValue;
            int count = dopValue.MeanValueList.Count;
            for (int i = 0; i < count; i++)
            {
                chart2.Series[0].Points.AddY(dopValue.MaxValueList[i]);
                chart2.Series[1].Points.AddY(dopValue.MinValueList[i]);
                chart2.Series[2].Points.AddY(dopValue.MeanValueList[i]);
                chart2.Series[3].Points.AddY(dopValue.VarianceList[i]);
            }
        }
        #endregion

        #region//复位表格所有曲线的数据
        /// <summary>
        /// 复位表格所有曲线的数据
        /// </summary>
        void ResetChart2()
        {
            for (int i = 0; i < chart2.Series.Count; i++)
            {
                chart2.Series[i].Points.Clear();
            }
        }
        #endregion

        #region//表格选择区域变化时执行的事件
        /// <summary>
        /// 表格选择区域变化时执行的事件
        /// </summary>
        /// <param name="e"></param>
        void SelectionChangedEvent(object sender, CursorEventArgs e)
        {
            if (e.Axis.AxisName == AxisName.X)
            {
                double TimeOfDay = e.Axis.ScaleView.ViewMaximum - e.Axis.ScaleView.ViewMinimum;
                //横坐标显示的时间范围在一分钟以内，坐标间隔类型设置为“秒”
                if (TimeOfDay * 86400 <= 60)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Seconds;
                }
                //横坐标显示的时间范围在一小时以内，坐标间隔类型设置为“分钟”
                else if (TimeOfDay * 24 <= 1)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Minutes;
                }
                //横坐标显示的时间范围在两天以内，坐标间隔类型设置为“小时”
                else if (TimeOfDay <= 2)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Hours;
                }
                //横坐标显示的时间范围在60以内，坐标间隔类型设置为“天”
                else if (TimeOfDay < 60)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Days;
                }
            }
        }
        #endregion

        #region//缩小表格视角大小时执行的事件
        /// <summary>
        /// 缩小表格视角大小时执行的事件
        /// </summary>
        /// <param name="e">事件参数</param>
        void AxisViewChangedEvent(object sender, ViewEventArgs e)
        {
            if (e.Axis.AxisName == AxisName.X)
            {
                double TimeOfDay = e.Axis.ScaleView.ViewMaximum - e.Axis.ScaleView.ViewMinimum;
                //横坐标显示的时间范围在一分钟以内，坐标间隔类型设置为“秒”
                if (TimeOfDay * 86400 <= 60)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Seconds;
                }
                //横坐标显示的时间范围在一小时以内，坐标间隔类型设置为“分钟”
                else if (TimeOfDay * 24 <= 1)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Minutes;
                }
                //横坐标显示的时间范围在两天以内，坐标间隔类型设置为“小时”
                else if (TimeOfDay <= 2)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Hours;
                }
                //横坐标显示的时间范围在60以内，坐标间隔类型设置为“天”
                else if (TimeOfDay < 60)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Days;
                }
            }
        }
        #endregion

        #region//根据表格中的series建立legend列表，靠表格下方呈横排列
        /// <summary>
        /// 根据表格中的series建立legend列表，靠表格下方呈横排列
        /// </summary>
        /// <param name="chart"></param>
        void SetLegend(Chart chart)
        {
            //在表格中新增一个默认Legend，并使不可用，为自定义Legend的
            chart.Legends.Add(new Legend() { Enabled = false });
            //定义自定义Legend
            chart.Legends.Add(new Legend() { LegendStyle = LegendStyle.Row, Docking = Docking.Bottom, Alignment = System.Drawing.StringAlignment.Center });
            //在自定义Legend中根据曲线集合中的曲线添加对应图例，
            for (int i = 0; i < chart.Series.Count; i++)
            {
                chart.Legends[1].CustomItems.Add(new LegendItem() { Enabled = true, Color = chart.Series[i].Color, BorderColor = System.Drawing.Color.White, BorderWidth = 2 });
                chart.Legends[1].CustomItems[i].Tag = chart.Series[i];
                chart.Legends[1].CustomItems[i].Cells.Add(new LegendCell() { CellType = LegendCellType.Image, Image = chk_imagePath, ImageTransparentColor = System.Drawing.Color.Red });
                chart.Legends[1].CustomItems[i].Cells.Add(LegendCellType.SeriesSymbol, "", System.Drawing.ContentAlignment.MiddleCenter);
                chart.Legends[1].CustomItems[i].Cells.Add(LegendCellType.Text, chart.Series[i].Name, System.Drawing.ContentAlignment.MiddleCenter);
            }
        }
        #endregion

        #region//释放资源
        /// <summary>
        /// 释放资源
        /// </summary>
        public void ReleaseResources()
        {
            //复位表格
            ResetChart2();
            //释放表格所占用的资源
            chart2.Dispose();
        }
        #endregion

        #region 界面逻辑
        /// <summary>
        /// 用于选择是否显示当前曲线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Chart_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            System.Windows.Forms.DataVisualization.Charting.HitTestResult result = ((Chart)sender).HitTest(e.X, e.Y);
            if (result != null && result.Object != null)
            {
                // When user hits the LegendItem
                if (result.Object is LegendItem)
                {
                    // Legend item result
                    LegendItem legendItem = (LegendItem)result.Object;

                    // series item selected
                    Series selectedSeries = (Series)legendItem.Tag;

                    if (selectedSeries != null)
                    {
                        if (selectedSeries.Enabled)
                        {
                            selectedSeries.Enabled = false;
                            if (File.Exists(unchk_imagePath))
                            {
                                legendItem.Cells[0].Image = unchk_imagePath;
                            }
                        }
                        else
                        {
                            selectedSeries.Enabled = true;
                            if (File.Exists(chk_imagePath))
                            {
                                legendItem.Cells[0].Image = chk_imagePath;
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 保存表格图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            //  进行当前路径保存
            string currentDirectory = Directory.GetCurrentDirectory();

            // Create a new save file dialog
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            // Sets the current file name filter string, which determines 
            // the choices that appear in the "Save as file type" or 
            // "Files of type" box in the dialog box.
            saveFileDialog1.Filter = "Bitmap (*.bmp)|*.bmp|JPEG (*.jpg)|*.jpg|EMF (*.emf)|*.emf|PNG (*.png)|*.png|GIF (*.gif)|*.gif|TIFF (*.tif)|*.tif";
            saveFileDialog1.FilterIndex = 2;
            saveFileDialog1.RestoreDirectory = true;

            // Set image file format
            if (saveFileDialog1.ShowDialog() == true)
            {
                ChartImageFormat format = ChartImageFormat.Bmp;

                if (saveFileDialog1.FileName.EndsWith("bmp"))
                {
                    format = ChartImageFormat.Bmp;
                }
                else if (saveFileDialog1.FileName.EndsWith("jpg"))
                {
                    format = ChartImageFormat.Jpeg;
                }
                else if (saveFileDialog1.FileName.EndsWith("emf"))
                {
                    format = ChartImageFormat.Emf;
                }
                else if (saveFileDialog1.FileName.EndsWith("gif"))
                {
                    format = ChartImageFormat.Gif;
                }
                else if (saveFileDialog1.FileName.EndsWith("png"))
                {
                    format = ChartImageFormat.Png;
                }
                else if (saveFileDialog1.FileName.EndsWith("tif"))
                {
                    format = ChartImageFormat.Tiff;
                }
                //else if (saveFileDialog1.FileName.EndsWith("svg"))
                //{
                //    format = ChartImageFormat.Svg;
                //}

                // Save image
                chart2.SaveImage(saveFileDialog1.FileName, format);
            }

            Directory.SetCurrentDirectory(currentDirectory);
        }

        /// <summary>
        /// 用户控件启动加载项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            chart2.ChartAreas[0].AxisX.Interval = 1;
            chart2.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
        }

        /// <summary>
        /// 选择是否显示表格中的网格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            if (((CheckBox)sender).IsChecked == true)
            {
                chart2.ChartAreas[0].AxisX.MajorGrid.LineColor = System.Drawing.Color.Transparent;
                chart2.ChartAreas[0].AxisY.MajorGrid.LineColor = System.Drawing.Color.Transparent;
                chart2.ChartAreas[0].AxisY2.MajorGrid.LineColor = System.Drawing.Color.Transparent;
            }
            else
            {
                chart2.ChartAreas[0].AxisX.MajorGrid.LineColor = System.Drawing.Color.Black;
                chart2.ChartAreas[0].AxisY.MajorGrid.LineColor = System.Drawing.Color.Black;
                chart2.ChartAreas[0].AxisY2.MajorGrid.LineColor = System.Drawing.Color.Black;
            }
        }
        #endregion

        private void btnExportData_Click(object sender, RoutedEventArgs e)
        {
            //if (SimScenario.GlobalSimState != SimState.Runing)
            //{
            //    SaveFileDialog sfd = new SaveFileDialog();
            //    sfd.Filter = "文本文档|*.txt";
            //    if (sfd.ShowDialog() == true)
            //    {
            //        string filePath = sfd.FileName;
            //        string Declare = "GNSS仿真与测试开放实验室\r\n\r\n";
            //        string Content = "评估数据类型:" + EvaluationType + "\r\n\r\n";
            //        double globalMeanValue = dopValue.MeanValueList.Sum() / dopValue.MeanValueList.Count;
            //        string globalValue = "全时段最小值:" + dopValue.MinValueList.Min() + "     " + "全时段最大值:" + dopValue.MaxValueList.Max() + "     " + "全时段平均值:" + globalMeanValue + "\r\n\r\n";
            //        //string SaveTime = DateTime.Now.ToLongTimeString(); 暂时不添加保存时间
            //        string HeaderXYZKm = "        时间 (UTC)                最小值                    最大值                    平均值                    方差        \r\n";
            //        switch (EvaluationType)
            //        {
            //            case DopEnum.Coverage:
            //                HeaderXYZKm = "        时间 (UTC)                最小值                    最大值                    平均值                    方差        \r\n";
            //                break;
            //            case DopEnum.GDOP:
            //                break;
            //            case DopEnum.PDOP:
            //                break;
            //            case DopEnum.HDOP:
            //                break;
            //            case DopEnum.VDOP:
            //                break;
            //            case DopEnum.TDOP:
            //                break;

            //            case DopEnum.HNSP:
            //                break;
            //            case DopEnum.VNSP:
            //                break;
            //            case DopEnum.PNSP:
            //                break;
            //            case DopEnum.TNSP:
            //                break;
            //            default:
            //                break;
            //        }
            //        ////HeaderXYZKm = "        Time (UTC)              MinValue(m)                MaxValue(m)              MeanValue(m)               Variance        ";
            //        string SplitLine = "-----------------------    ----------------------    ----------------------    ----------------------    ----------------------\r\n";
            //        File.AppendAllText(filePath, Declare + Content + globalValue + HeaderXYZKm + SplitLine);
            //        for (int i = 0; i < dopValue.MaxValueList.Count; i++)
            //        {
            //            string content = dopValue.TimeList[i] + "                  " + dopValue.MinValueList[i].ToString().PadRight(22, ' ') +
            //                "    " + dopValue.MaxValueList[i].ToString().PadRight(21, ' ') +
            //                "    " + dopValue.MeanValueList[i].ToString("0.00").PadRight(21, ' ') +
            //                "    " + dopValue.VarianceList[i].ToString("0.00").PadRight(21, ' ') + "\r\n";
            //            File.AppendAllText(filePath, content);
            //        }
            //    }
            //    Directory.SetCurrentDirectory(SimScenario.startDirectory);
            //}
            //else
            //{
            //    MessageBox.Show("请先暂停再保存数据!");
            //}
            
        }

        public void ReleaseData()
        {
            //throw new NotImplementedException();
        }
    }
}
